<template lang="html">
<ul class="mineDetail">
    <div class="uploadImgItem" v-on:click="chooseImg">
        <div class="left">
            <p class="p1">上传照片<!--<span>(本人清晰正脸照,不公开）</span>--></p>
           <p class="p2">上传头像享受人脸识别、无需排队等超级福利</p>
        </div>
        <div class=right  >
            <img   :src="imgSrc"/>
        </div>

    </div>
    <li class="item" style="height: 0.55rem;line-height: 0.55rem;">
        <span>头像</span>
        <img  :src='(userData.obj.hasOwnProperty("headimgurl") && userData.obj.headimgurl.length>5)?userData.obj.headimgurl:"/static/images/default_avatar-v2.png"' alt="">

    </li>
    <li class="item">
         <span>用户名</span>
        <span>{{userData.des}}</span>
    </li>
    <li class="item">
          <span>昵称</span>
          <span>{{myNickname}}</span>
        <!--<span>{{userData.obj.nickname}}</span>-->
    </li>
    <li class="item">
          <span>性别</span>
        <span>{{sex}}</span>
    </li>
    <div class="imgContent" v-show="isShowImg">
        <div class="upload_btn" v-on:click="upLoadImg" v-show="isShowBtn">上传图片</div>
        <img  :src="imgSrc" alt=""  ref="imgSrc">
        <!--<span>localIds:{{localIds}}</span>
        <span>serverId:{{serverId}}</span>
        <span>upLoadServerIdData:{{upLoadServerIdData}}</span>-->
    </div>
</ul>
</template>

<script>
    import axios from 'axios'
    import router from '../router/router'
    import { Indicator,Toast } from 'mint-ui';
    export default {
        data: function() {
            return {
                userData: "",
                responseData: "",
                imgSrc:"../../static/images/icon_camera.png",
                localIds: "",
                serverId: "",
                isShowBtn: false,
                upLoadServerIdData: "",
                isShowImg: false,
                isAndroid:"",
                isIOS:"",
                sex:"",
                myNickname:""
            }
        },

        created: function() {
            moveAction();
            this.deviceType();
            this.getFaceImgFromServer();
            this.$store.commit('changeIndexConf', {
                isFooter: false,
                isToast: false,
            });
            this.getInfo();

        },
        mounted:function(){
             $(".com-app").css("background","#f6f6f6")

        },
        methods: {
            getInfo: function() {
                var userInfo = JSON.parse(store.get("userInfo"));
                if (! userInfo.obj.nickname) {
                    this.myNickname="麦铺小粉丝";
                }else{
                    this.myNickname=userInfo.obj.nickname;
                }
                this.userData = userInfo;
                this.getSex(this.userData.obj.sex)
            },
            chooseImg: function() {
                this.isShowBtn = false;
                var _this = this;
                wx.chooseImage({
                    count: 1, // 默认9
                    sizeType: ['compressed'], // 可以指定是原图还是压缩图，默认二者都有
                    sourceType: ['camera'], // 可以指定来源是相册还是相机，默认二者都有
                    success: function(res) {

                        _this.localIds = res.localIds[0]; // 返回选定照片的本地ID列表，localId可以作为img标签的src属性显示图片
                        _this.imgSrc=res.localIds[0];
                        // _this.imgLoad();
                        _this.isShowImg = true;
                        // if(_this.isIOS){
                          wx.getLocalImgData({
                             localId: res.localIds[0],
                             success: function (res) {
                               var pre="data:image/jpeg;base64,"
                                if(_this.isIOS){
                                  _this.imgSrc= res.localData.replace('jgp', 'jpeg');
                                }else{
                                  _this.imgSrc=pre+res.localData;
                                }
                                _this.faceChecks(_this.imgSrc)
                             },
                             fail:function(){
                                   Toast({
                                     message: '微信接口调用失败',
                                     position: 'middle',
                                     duration: 1000
                                     });
                             }
                           });
                    },
                    fail:function(){
                          Toast({
                            message: '微信接口调用失败',
                            position: 'middle',
                            duration: 1000
                            });
                    }
                });
            },
            previewImg: function() {
                wx.previewImage({
                    current: '', // 当前显示图片的http链接
                    urls: [] // 需要预览的图片http链接列表
                });
            },
            upLoadImg: function() {

                var _this = this;
                Indicator.open({
                    text: '上传中...',
                    spinnerType: 'triple-bounce'
                    });
                wx.uploadImage({
                    localId: _this.localIds, // 需要上传的图片的本地ID，由chooseImage接口获得
                    isShowProgressTips: 0, // 默认为1，显示进度提示
                    success: function(res) {

                        _this.serverId = res.serverId; // 返回图片的服务器端ID
                        _this.upLoadServerId(res.serverId);

                    },
                       fail:function(res){
                        // alert("fail:"+res.toString())
                         Indicator.open({
                            text: '上传失败...',
                            spinnerType: 'triple-bounce'
                            });
                            Indicator.close();
                    },
                    complete:function(res){
                        //  alert("com:"+res.toString())
                    }
                });
            },
            upLoadServerId: function(serverid) {
                var _this = this;
                axios.get('/member/uploadMemberIcon', {
                        params: {
                            serverId: serverid
                        }
                    })
                    .then(function(response) {
                        // console.log(response);
                        let responseData = JSON.parse(response.data)
                        _this.upLoadServerIdData = responseData
                        if (responseData.code == 1) {
                            Indicator.close();
                            _this.$store.commit('changeIndexConf', {
                                isToast: true,
                                toastTip: "上传成功"
                            });
                            _this.imgSrc = responseData.url;
                            _this.isShowBtn = false;
                            setTimeout(function() {
                                _this.$store.commit('changeIndexConf',   {                    
                                    isToast: false,
                                     toastTip:   ""                
                                });
                                _this.isShowImg = false;
                            }.bind(_this), 800)

                        } else {
                              Indicator.close();
                            _this.$store.commit('changeIndexConf', {
                                isToast: true,
                                toastTip: responseData.msg
                            });
                            setTimeout(function() {
                                _this.$store.commit('changeIndexConf',   {                    
                                    isToast: false,
                                     toastTip:   ""                
                                });
                            }.bind(_this), 800)
                        }
                    })
                    .catch(function(error) {
                        console.log(error);
                    });
            },
           faceChecks:function(dataBase64) {
             var _this=this;

             Indicator.open({
                text: '人脸检测中，请稍等...',
                spinnerType: 'fading-circle'
              })
              $.ajax({
                  type: "POST",
                  url: "https://api-cn.faceplusplus.com/facepp/v3/detect",
                  data: {
                      api_key: "aq_V9Y0zlQyq-i2jFQ2piQMWgo1O0Atu",
                      api_secret: "DPm47sD5aEeDWxQFpd7WeYKs3mQHQn98",
                      image_base64: dataBase64.split(",")[1],
                      return_landmark:1,
                      return_attributes:"gender,age,smiling,headpose,facequality,blur,eyestatus,emotion,ethnicity"
                  },
                  success: function(data) {

                      Indicator.close();
                      var faceLength=data.faces.length;//人脸个数
                      if (faceLength==0) {
                        Toast({
                          message: '未检测到人脸，请重新选择',
                          position: 'middle',
                          duration: 2000
                          });
                          return;
                      }
                      var facequality=data.faces[0].attributes.facequality.value,//人脸质量
                          face_threshold=80,//人脸质量判断阀值
                          blurness=data.faces[0].attributes.blur.blurness.value,//新的人脸模糊分析结果
                          blur_threshold=50;//人脸模糊判断阀值
                      if (faceLength>1) {
                        Toast({
                          message: '检测到多张人脸，请重新选择'/**+facequality*/,
                          position: 'middle',
                          duration: 2000
                          });
                          return;

                      }
                      if (facequality<face_threshold) {
                        Toast({
                          message: '人脸质量过低,请重新拍照，并确保五官正对摄像头'/**+facequality**/,
                          position: 'middle',
                          duration: 2000
                        });
                          return;
                      }
                      if (blurness>blur_threshold) {
                        Toast({
                          message: "人脸质量过低,请重新拍照"/**+facequality+"||模糊度："+blurness*/,
                          position: 'middle',
                          duration: 2000
                        });
                        return;
                      }
                      if (faceLength == 1 && facequality>=face_threshold &&blurness<blur_threshold) {
                        _this.isShowBtn = true;
                        Toast({
                          message: '人脸检测成功，请上传'/**+facequality+"||模糊度："+blurness*/,
                          position: 'middle',
                          duration: 2000
                          });
                          return;
                      }

                  },
                  error: function(err) {
                      Indicator.close();
                      Toast({
                        message: '人脸检测失败，请重新拍照',
                        position: 'middle',
                        duration: 1000
                        });
                  }
              })

          },
            getFaceImgFromServer: function() {
                var _this = this;
                axios.get('/member/getFaceImg')
                    .then(function(response) {
                        let resData = JSON.parse(response.data)
                            // console.log(resData);
                        if (!resData.url) {
                            _this.imgSrc = "../../static/images/icon_camera.png";
                            _this.isShowImg = true;
                        } else {
                            _this.isShowImg = false;
                            _this.imgSrc = resData.url;
                        }
                    })
                    .catch(function(error) {
                        console.log(error);
                    });
            },
            deviceType:function(){
              var u = navigator.userAgent, app = navigator.appVersion;
              this.isAndroid = u.indexOf('Android') > -1 || u.indexOf('Linux') > -1; //g
              this.isIOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端
            },
            getSex:function(sex){
                switch (sex) {
                    case "1":
                        this.sex = "男";
                        break;
                    case "0":
                          this.sex = "女";
                        break;
                    default:
                          this.sex = "未知";
                        break;
                }


            }

        }
    }
</script>

<style lang="scss" scoped>
    @import "../../static/css/mineDetail.scss";
</style>
